import re
from urllib.parse import urljoin
from retrying import retry
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
import os
from log import logger


# 资源管理界面投运资源
@retry(stop_max_attempt_number=3)
def resource_archives(driver, web, *args, **kwargs):
    logger.info('资源管理界面投运资源巡检')
    # 拼接url
    url = urljoin(kwargs.get('url'), kwargs.get('path'))
    data = kwargs.get('data')
    file_path = kwargs.get('files')
    # 构造负控单元数据结果
    result = kwargs.get('result')

    # 切换到资源管理的界面
    driver.get(url)
    logger.info('开始计算投运项目数量')
    print('开始计算投运项目数量')
    # 获取资源状态表头
    web.until(
        EC.visibility_of_element_located((By.XPATH, "//thead[@class='has-gutter']/tr//*[contains(text(), '资源状态')]"))
    ).click()

    web.until(
        EC.visibility_of_element_located(
            (By.XPATH, "//div[@class='el-table-filter']//div[@role='group']//span[contains(text(), '投运')]"))
    ).click()

    web.until(
        EC.presence_of_element_located((By.XPATH, "//div[@class='el-table-filter']//button[contains(text(), '筛选')]"))
    ).click()
    time.sleep(1)
    total_num = 0
    # 获取投运数量
    try:
        # 尝试获取设备总数
        total_str = web.until(EC.presence_of_element_located((By.XPATH, "//span[@class='el-pagination__total']"))).text
        # 过滤汉字，只保留数字
        pattern = '[\u4e00-\u9fa5]{0,}'
        total_num = int(re.sub(pattern, '', total_str))
        logger.info('投运项目总数: {}'.format(total_num))
        print('投运项目总数: {}'.format(total_num))
    except:
        logger.info('没有投运的项目')
        print('没有投运的项目')

    pic = os.path.join(file_path, '投运资源.png')
    driver.save_screenshot(pic)
    now = time.localtime()
    formatted_time = time.strftime("%Y年%m月%d日", now)
    result = "截止{}，已并网项目数为{}个"
    logger.info(result.format(formatted_time, total_num))
    print(result.format(formatted_time, total_num))
    return result.format(formatted_time, total_num)


# # 2、已并网项目数据采集状态
@retry(stop_max_attempt_number=3)
def dataStatistics(driver, web, *args, **kwargs):
    '''
    :param driver:
    :param web:
    :param args:
    :param kwargs:
    :return: 返回数据采集状态
    '''
    logger.info('已并网项目数据采集状态巡检')
    # 拼接url
    url = urljoin(kwargs.get('url'), kwargs.get('path'))
    data = kwargs.get('data')
    file_path = kwargs.get('files')
    # 构造负控单元数据结果
    result = kwargs.get('result')

    # 切换到数据采集的页面
    driver.get(url)
    print('开始巡检已并网项目数据采集状态')
    logger.info('开始巡检已并网项目数据采集状态')
    time.sleep(3)
    web.until(
        EC.visibility_of_element_located((By.XPATH, "//*[contains(text(), '投运中')]"))
    ).click()
    logger.info('切换到投运中的页面')
    print('切换到投运中的页面')

    result = "已并网{}个商业负荷数据采集正常, {}存在漏采"
    loucai = []
    total = len(data[0]['资源数据采集'])
    print('巡检的并网项目总数： {}'.format(total))
    logger.info('巡检的并网项目总数： {}'.format(total))
    # 输出更新后的层级数据结构
    for item in data:
        for key, value in item.items():
            for item in value:
                for k, v in item.items():
                    print("当前巡检的项目为：{}".format(v))
                    logger.info("当前巡检的项目为：{}".format(v))
                    time.sleep(0.5)
                    # 查找并网资源的数据曲线
                    # 查找公司
                    web.until(
                        EC.visibility_of_element_located(
                            (By.XPATH, "//span[contains(@class, 'level-2')]//span[@title='{}']".format(k)))
                    ).click()
                    # 查找楼宇
                    web.until(
                        EC.visibility_of_element_located(
                            (By.XPATH, "//span[contains(@class, 'level-3')]//span[@title='{}']".format(v)))
                    ).click()
                    time.sleep(1)
                    try:
                        web.until(
                            EC.visibility_of_element_located((By.XPATH, "//*[contains(text(), '存在漏采')]"))
                        )
                        print('当前巡检的项目：{} 存在漏采'.format(v))
                        logger.info('当前巡检的项目：{} 存在漏采'.format(v))
                        # web.until(
                        #     EC.visibility_of_element_located((By.XPATH, data_callback))
                        # ).click()
                        # # time.sleep(1)
                        # web.until(
                        #     EC.visibility_of_element_located((By.XPATH, button_call))
                        # ).click()
                        # # time.sleep(1)
                        # web.until(
                        #     EC.visibility_of_element_located((By.XPATH, button_ok))
                        # ).click()
                        # # time.sleep(1)
                        # web.until(
                        #     EC.visibility_of_element_located((By.XPATH, return_pre_page))
                        # ).click()
                        loucai.append(v)
                    except:
                        print('当前巡检的项目：{} 没有漏采'.format(v))
                        logger.info('当前巡检的项目：{} 没有漏采'.format(v))

                    # 截图
                    time.sleep(1)
                    pic = os.path.join(file_path, '{}.png'.format(v))
                    driver.save_screenshot(pic)
                    # 收敛下拉框
                    web.until(
                        EC.visibility_of_element_located(
                            (By.XPATH, "//span[contains(@class, 'level-2')]//span[@title='{}']".format(k)))
                    ).click()

    total -= len(loucai)
    print(result.format(total, ",".join(loucai)))
    logger.info(result.format(total, ",".join(loucai)))

    return result.format(total, ",".join(loucai))
